﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AppProperties = WPF.TestEditor.Properties;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.CodeCompletion;
using WPF.TestEditor.Common;
using ICSharpCode.AvalonEdit.Editing;
using EasyStep.Business.Interfaces;
using EasyStep.Attributes;
using ICSharpCode.AvalonEdit;
using EasyStep.Data.Entities;

namespace WPF.TestEditor.Controls
{

    public partial class ConstantsTextEditor : UserControlBase
    {
        public ConstantsTextEditor()
            : base()
        {
            InitializeComponent();
            txtCEditor.TextArea.TextEntering += TextArea_TextEntering;
            txtCEditor.TextArea.TextEntered += TextArea_TextEntered;
            txtCEditor.HighlightLine += new EventHandler<ColorizingLineEventArgs>(txtCEditor_HighlightLine);     

            if (TestDataContext != null) InitEditor();
        }

        void txtCEditor_HighlightLine(object sender, ColorizingLineEventArgs e)
        {
            var index = e.LineText.IndexOf("=");
            e.OnHighlightLineSegment(e.lineStartOffset + 0, e.lineStartOffset + 0 + (index < 0 ? e.LineText.Length : index),txtCEditor.SyntaxHighlighting.GetNamedColor("Constants"));
            if (index < 0) return;
            var rightpart = e.LineText.Substring(index + 1);
            var leftpart = e.LineText.Substring(0, index);
            var correct=!leftpart.Trim().Equals(rightpart.Trim(),StringComparison.OrdinalIgnoreCase);
            e.OnHighlightLineSegment(e.lineStartOffset + index + 1, e.lineStartOffset + e.LineText.Length, 
                txtCEditor.SyntaxHighlighting.GetNamedColor(correct?"CorrectConstant":"IncorrectConstant")
            );
        }

        void TextArea_TextEntered(object sender, TextCompositionEventArgs e)
        {
            var area = (sender as TextArea);
            if (area == null || e.Text.Trim().Equals("")) return;            
        }
        void TextArea_TextEntering(object sender, TextCompositionEventArgs e)
        {
            
        }

        public void InitEditor()
        {
            //initialize text editor
            try
            {
                txtCEditor.SyntaxHighlighting = GetSyntaxHighlighter("ConstEditor", AppProperties.Settings.Default.ConstantsEditorHighlightingTemplate, (template) =>
                {
                    return template;
                });
            }
            catch (Exception ex)
            {
                if (TestDataContext!=null) TestDataContext.Log.Fatal("Can't initialize highlighting for constants", ex);
            }

        }
    

        private string EscapeSpecChars(string s)
        {
            StringBuilder sb = new StringBuilder(s);
            var r = "[\\^$.|?*+(){}";
            for (int i = 0; i < r.Length; i++)
                sb.Replace(r[i].ToString(), "\\" + r[i].ToString());
            return sb.ToString();
        }
        private IHighlightingDefinition GetSyntaxHighlighter(string name, string filePath, Func<string, string> processFileText)
        {
            var themePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filePath), AppProperties.Settings.Default.CurrentTheme, System.IO.Path.GetFileName(filePath));
            if (System.IO.File.Exists(themePath))
                filePath = themePath;
            if (!System.IO.File.Exists(filePath))
            {
                TestDataContext.Log.Error("Can't find xml highlighting template by path:" + filePath);
                return null;
            }
            var xmlText = System.IO.File.ReadAllText(filePath);
            xmlText = processFileText(xmlText);
            if (string.IsNullOrEmpty(xmlText))
            {
                TestDataContext.Log.Error("Empty xml highlighting template, path:" + filePath);
                return null;
            }
            IHighlightingDefinition result = null;
            using (var tr = new System.IO.StringReader(xmlText))
            using (var xr = new System.Xml.XmlTextReader(tr))
            {
                result = ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(xr, HighlightingManager.Instance);
            }
            var existing = HighlightingManager.Instance.GetDefinition(name);
            if (existing == null)
                HighlightingManager.Instance.RegisterHighlighting(name, new string[] { ".txt" }, result);
            else
            {
                existing.MainRuleSet.Spans.Clear();
                foreach (var item in result.MainRuleSet.Spans)
                    existing.MainRuleSet.Spans.Add(item);
            }
            return result;
        }

        public string Text
        {
            get { return txtCEditor.Text; }
            set { txtCEditor.Text = value; }
        }

    }
}
